package org.bjf.modules.monitor.web;

import cn.dev33.satoken.annotation.SaCheckPermission;
import org.apache.commons.lang3.StringUtils;
import org.bjf.cache.CacheNameConfig;
import org.bjf.modules.monitor.service.MonitorService;
import org.bjf.modules.sys.annotation.AuthModule;
import org.bjf.security.satoken.SaTokenAdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("admin")
@AuthModule(code = "monitor", desc = "字典管理")
public class MonitorController {

    @Autowired
    private MonitorService monitorService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 服务器信息
     */
    @RequestMapping("monitor/serverInfo")
    @SaCheckPermission(value = "monitor-read", orRole = "super-admin", type = SaTokenAdminUtil.TYPE)
    @Cacheable(value = CacheNameConfig.RedisCacheEnum.Names.FAST, key = "'live:monitor:serverinfo'")
    public Object getServerInfo() {
        return monitorService.getServerInfo();
    }

    /**
     * redis信息
     */
    @RequestMapping("monitor/redisInfo")
    @SaCheckPermission(value = "monitor-read", orRole = "super-admin", type = SaTokenAdminUtil.TYPE)
    @Cacheable(value = CacheNameConfig.RedisCacheEnum.Names.FAST, key = "'live:monitor:redisinfo'")
    public Object getRedisInfo() {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info());
        Properties commandStats = (Properties) redisTemplate.execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) connection -> connection.dbSize());

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);

        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return result;
    }


}
